/**
 * 
 */
package com.sebscape.sebcms.pages.actions;

import java.util.HashSet;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.opensymphony.xwork2.ActionSupport;
import com.sebscape.sebcms.Constants;
import com.sebscape.sebcms.pages.domain.Page;
import com.sebscape.sebcms.pages.persistence.PageDao;
import com.sebscape.sebcms.tools.Utils;

/**
 * @author Stephen
 *
 */
public class PageActions extends ActionSupport {

	private static final long serialVersionUID = 703047536624387811L;

	private static Log log = LogFactory.getLog(PageActions.class);
	private String name; // passed as a parameter.
	private String id; // passed as a parameter.
	
	private Page page;
	
	/**
	 * Setup for the action. We need the Page initialized so setters do not throw NPE's.
	 */
	public PageActions(){
		super();
		this.page = new Page();
	}
	
	/**
	 * The load function meant to be called when end-users browse pages.
	 * @return
	 */
	public String view(){
		// the page should have already been loaded by the CmsPageLoaderInterceptor.
		if( ServletActionContext.getRequest().getAttribute( Constants.ATTRIB_PAGE ) == null ){
			Page page = null; // the page we will fetch and put in the Request scope.
			// get a DAO.
			PageDao dao = new PageDao();
			// get the filter.
			try {
				Long pid = Long.valueOf( id );
				page = dao.load( pid );
			} catch (NumberFormatException e) {
				log.debug("PageActions.view: could not fetch by id-param, " +
						"so try name-param = " + name );
				page = dao.findByName( name );
			}
			if( page != null ){
				log.debug("PageActions.view: found page name = " + page.getName() );
				ServletActionContext.getRequest().setAttribute( Constants.ATTRIB_PAGE, page);
				return SUCCESS;
			} else {
				log.debug("Page not found - Did you include a valid name= or id= in the url?");
				return ERROR;
			}
		} else {
			return SUCCESS;
		}
	}
	
    /**
     * Load instance of the Page Object.
     * requires to be in Request:
     *   Constants.PARAM_ID
     * @return
     */
	public String load(){
        String id = Utils.getRequestValue( ServletActionContext.getRequest(),
                                Constants.PARAM_ID, null );
        PageDao dao = new PageDao();
        try {
            Page p = dao.load( Long.valueOf( id ) );
            ServletActionContext.getRequest().setAttribute(Constants.ATTRIB_PAGE, p );
            log.debug("load completed; returning SUCCESS.");
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ERROR;
    }

    /**
     * Save the Page
     * @return
     */
	public String save(){
    	if( page != null ){
	    	PageDao dao = new PageDao();
	    	try {
	    		log.debug("saving page with isPublic = " + page.getIsPublic() );
	    		Page newObj = dao.save( page );
	    		ServletActionContext.getRequest().setAttribute(Constants.ATTRIB_USER, newObj );
	    		log.debug("save user completed; returning SUCCESS.");
	    		return SUCCESS;
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    	}
	    	return ERROR;
    	}
    	return "RETRY";
    }

	   /**
     * Update the persistedObject in the database. REQUIRES that the PersistedObject implement 
     * the interface IUpdateable.
     * @return
     */
	public String update(){
    	// get the id.
        PageDao dao = new PageDao();
		try {
			Page p = dao.update( page );
			ServletActionContext.getRequest().setAttribute(Constants.ATTRIB_PAGE, p );
			log.debug("update completed; returning SUCCESS.");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ERROR;
    }

	/**
	 * Delete the Page
	 * @return
	 */
	public String delete(){
		PageDao dao = new PageDao();
		try {
			Long id = Long.valueOf( (String)ServletActionContext.getRequest().getParameter( "id" ) );
			log.debug("deleting page with id = " + id );
			dao.delete( id );
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	/////////////////////////////////
	// Parameter Getters and Setters
	/////////////////////////////////

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the page
	 */
	public Page getPage() {
		return page;
	}

	/**
	 * @param page the page to set
	 */
	public void setPage(Page page) {
		this.page = page;
	}
	
	/**
	 * Set the list of Groups.
	 * @param groupIdList
	 */
	public void setGroupIdList( List<Long> groupIdList ){
		this.page.setGroupKeySet( new HashSet<Key>() );
		log.debug("setGroupIdList called..." );
		for( Long id: groupIdList ){
			Key key = KeyFactory.createKey( "Page", id);
			log.debug("adding key: " + id + " as " + key );
			this.page.getGroupKeySet().add( key );
		}
	}
	
}
